import java.util.Arrays;

public class MyArrayList {
    private int[] elem;
    private int usedSize;
    private static final int DEFAULT_SIZE = 10;

    public MyArrayList() {
        this.elem = new int[DEFAULT_SIZE];
    }

    public MyArrayList(int initialSize) {
        this.elem = new int[initialSize];
    }

    public void display() {
        for (int i = 0; i < this.usedSize; i++) {
            System.out.print(this.elem[i] + " ");
        }
    }

    public boolean isFull() {
        if (this.usedSize == this.elem.length) {
            return true;
        }
        return false;
    }

    public void add(int data) {
        if (isFull()) {
            this.elem = Arrays.copyOf(this.elem, 2 * this.elem.length);
        }
        this.elem[this.usedSize++] = data;
    }

    // ！！！容易出错的地方
    public void add(int pos,int data) {
        if (pos < 0 || pos > this.usedSize) {
            throw new IllegalPositionException("位置不合法");
        }
        if (isFull()) {
            this.elem = Arrays.copyOf(this.elem, 2 * this.elem.length);
        }
        for (int i = this.usedSize-1; i >= pos ; i--) {
            this.elem[i+1] = this.elem[i];
        }
        this.elem[pos] = data;
        this.usedSize++;
    }
    public boolean contains(int toFind) {
        for (int i = 0; i < this.usedSize; i++) {
            if(this.elem[i] == toFind) {
                return true;
            }
        }
        return false;
    }
    public int indexOf(int toFind) {
        for (int i = 0; i < this.usedSize; i++) {
            if(this.elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }
    public int get(int pos) {
        if (pos < 0 || pos >= this.usedSize) {
            throw new IllegalPositionException("位置不合法");
        }
        return this.elem[pos];
    }
    // 给 pos 位置的元素设为 value [更新]
    public void set(int pos, int value) {
        if (pos < 0 || pos >= this.usedSize) {
            throw new IllegalPositionException("位置不合法");
        }
        this.elem[pos] = value;
    }
    public int size() {
        return this.usedSize;
    }
    public void clear() {
        /*for (int i = 0; i < this.usedSize; i++) {
            this.elem[i] = null;
        }*/
        this.usedSize = 0;
    }
    // ！！！容易出错的地方
    public void remove(int toRemove) {
        int index = indexOf(toRemove);
        if(index == -1) {
            System.out.println("没有这个数据！");
            return;
        }
        for (int i = index; i < this.usedSize-1; i++) {
            this.elem[i] = this.elem[i+1];
        }
        //this.elem[usedSize-1] = null;
        this.usedSize--;
    }
}
